<?php
/**
 * Serves an internal file relative to STATIC_DIR only
 * 
 *     SCMwiki Copyright (C) 2010  Callan Bryant <callan1990@googlemail.com>
 *     
 *     Based on Voswork - A simple, fast PHP filesystem abstraction layer
 *     Voswork Copyright (C) 2010  Callan Bryant <callan1990@googlemail.com>
 * 
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY. without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * 
 * @package main
 * @author Callan Bryant <callan1990@googlemail.com>
 */

/**
 * Serves an internal file relative to STATIC_DIR only
 * 
 * Just instantiate it with the given internal file reference. It will use
 * the HTTP server class to safely and quickly serve the requested file.
 * 
 * @author Callan Bryant
 */
class internalFile
{	
	protected $response;

	public function __construct($file)
	{
		// instantiate the HTTP class
		$this->response = new httpResponse();

		$this->file = self::absolute($file);

		// it's just necessary to see if the file is legal.
		// the http class will handle forbidden or not found!
		if (!self::legal($this->file))
			$this->response->status = 403;
		else
		{
			// everything is ok, serve file with HTTP class
			$this->response->load_local_file($this->file);

			if (PERSISTENT_STATIC_FILES)
				$this->response->persistent = true;
		}
		$this->response->serve();
	}

	/**
	 * sanity check on given file
	 * @param string $path absolute path to file
	 * @return int true or false: is the file sane?
	 */
	public static function legal($path)
	{
		// verify it is within the STATIC_DIR
		// realpath is used to allow the use of symbolic links etc
		if (strpos($path,realpath(INCLUDE_DIR)) !== 0)
			return false;

		// file is legal
		return true;
	}

	/**
	 * Returns the real internal path given the dirty path relative to 
	 * STATIC_DIR
	 */
	public static function absolute($path)
	{
		return realpath(INCLUDE_DIR.'/'.$path);
	}
}
?>
